package com.glo.spreadsheet2db.services.jdbc.service;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.glo.spreadsheet2db.model.Spreadsheet;
import com.glo.spreadsheet2db.model.SpreadsheetCell;
import com.glo.spreadsheet2db.services.AbstractSpreadsheet2DbService;
import com.glo.spreadsheet2db.services.repositories.SpreadsheetCellRepository;
import com.glo.spreadsheet2db.services.repositories.SpreadsheetRepository;
import com.google.gdata.util.ServiceException;

@Service
//@Scope("Request")
public class JdbcSpreadsheet2DbService extends AbstractSpreadsheet2DbService {

	@Autowired
	private SpreadsheetCellRepository spreadsheetCellRepository;
	
	@Autowired
	private SpreadsheetRepository spreadsheetRepository;

	@Transactional(readOnly = true)
	public Spreadsheet getSpreadsheetById(long id) {
		List<SpreadsheetCell> rows = this.spreadsheetCellRepository.getSpreadsheetCellBySheetId(id);
		
		Spreadsheet spreadsheet = this.spreadsheetRepository.getSpreadsheetById(id);		
		
		spreadsheet.attachCells(rows);
		
		return spreadsheet;
	}

	@Transactional
	public Spreadsheet saveSpreadsheet(Spreadsheet spreadsheet) {
		
		spreadsheet = this.spreadsheetRepository.saveSpreadsheet(spreadsheet);
		
		for (SpreadsheetCell spreadsheetCell : spreadsheet.getCellsList()) {
			this.spreadsheetCellRepository.saveSpreadsheetCell(spreadsheetCell);
		}

		return spreadsheet;
	}

	public Spreadsheet importAndSaveSpreadsheet(String username,
			String password, String spreadsheetName) throws IOException,
			ServiceException {
		Spreadsheet spreadsheet = importSpreadsheet(username, password, spreadsheetName);
		return saveSpreadsheet(spreadsheet);
	}
}
